import win32gui
import win32process
import win32api
import win32con
import ctypes
import logging
from ctypes import wintypes
from utils.config import ConfigManager

class PositionReader:
    def __init__(self, hwnd):
        self.hwnd = int(hwnd)  # 当前窗口句柄
        self.process_handle = None
        self.base_address = None
        
        # 从配置文件获取偏移
        config = ConfigManager()
        self.X_OFFSET = config.coordinate_x_offset
        self.Y_OFFSET = config.coordinate_y_offset
        
        self.last_pos = None
        print(self.hwnd)
        # 获取窗口标题和进程信息
        try:
            self.window_title = win32gui.GetWindowText(self.hwnd)
            _, self.process_id = win32process.GetWindowThreadProcessId(self.hwnd)
            logging.info(f"初始化窗口: {self.window_title} (PID: {self.process_id})")
        except Exception as e:
            logging.error(f"获取窗口信息失败: {e}")
            
        if not self.init():
            logging.error("初始化失败！")

    def init(self):
        try:
            # 打开进程
            self.process_handle = win32api.OpenProcess(
                win32con.PROCESS_VM_READ | 
                win32con.PROCESS_QUERY_INFORMATION | 
                win32con.PROCESS_VM_OPERATION,
                False, 
                self.process_id
            )
            
            # 查找模块
            modules = win32process.EnumProcessModules(self.process_handle)
            for module in modules:
                try:
                    module_path = win32process.GetModuleFileNameEx(self.process_handle, module)
                    if "gacrunner64.dll" in module_path.lower():
                        self.base_address = module
                        break
                except:
                    continue
            
            if not self.base_address:
                print("未找到目标模块!")
                return False
                
            return True
            
        except Exception as e:
            logging.error(f"初始化过程中发生错误: {e}")
            return False

    def _read_memory(self, offset):
        """读取内存"""
        try:
            if not self.process_handle or not self.base_address:
                return None
                
            actual_address = self.base_address + offset
            buffer = ctypes.c_uint32()
            bytes_read = ctypes.c_size_t()
            
            result = ctypes.windll.kernel32.ReadProcessMemory(
                int(self.process_handle),
                ctypes.c_void_p(actual_address),
                ctypes.byref(buffer),
                ctypes.sizeof(buffer),
                ctypes.byref(bytes_read)
            )
            
            return buffer.value if result else None
            
        except Exception as e:
            logging.error(f"读取内存失败: {e}")
            return None

    def get_position(self):
        """获取坐标"""
        x = self._read_memory(self.X_OFFSET)
        y = self._read_memory(self.Y_OFFSET)
        
        if x is not None and y is not None:
            current_pos = (x, y)
            # 只在位置变化时打印
            if self.last_pos != current_pos:
                # print(f"{self.window_title} 坐标: {current_pos}")
                self.last_pos = current_pos
            return current_pos
        return self.last_pos  # 如果读取失败，返回上一次的有效位置
        
    def close(self):
        if self.process_handle:
            win32api.CloseHandle(self.process_handle) 